package me.luger.core.commom.util;

import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * Created by Administrator on 2017/4/24 0024.
 */
public class ImgUtil {
    public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr.replace("data:image/jpeg;base64,", ""));
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            File imgFile = new File(imgFilePath);
            FileUtil.forceMkdir(imgFile.getParentFile());
            if(imgFile.exists()){
                imgFile.delete();
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            LogUtil.errorLog(e,"ImgUtil.GenerateImage error");
            return false;
        }
    }
}
